<template>
  <div>
    <h2>vue3的生命周期</h2>
    <div id="dom">{{ msg }}---{{ num }}</div>
    <!-- v-on时间绑定 -->
    <button @click="handleClick">click me</button><br />
    <input type="text" placeholder="请输入姓名" v-model="username" /><br />
    <input
      type="text"
      placeholder="请输入电话"
      v-model="userphone"
      @blur="handleblur"
      @focus="handlefocus"
      @input="handleInput"
    /><br />
    <textarea
      placeholder="请输入您的建议"
      cols="30"
      rows="10"
      v-model="userInput"
    ></textarea>
    <p>{{ username }}--{{ userInput }}</p>
    <button @click="submit">提交</button>
  </div>
</template>
<script>
import {
  reactive,
  toRefs,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
} from "vue";
export default {
  name: "about",
  setup() {
    const data = reactive({
      msg: "你好",
      msg2: "你好2",
      num: 0,
      username: "",
      userInput: "",
      userphone: "",
    });
    // 数据渲染前
    onBeforeMount(() => {
      console.log("onBeforeMount", document.querySelector("#dom"));
    });
    // 数据渲染后
    onMounted(() => {
      console.log("onMounted", document.querySelector("#dom"));
      //定时器
      setInterval(() => {
        data.msg = "hello";
        // data.msg2 = "hello";
      }, 2000);
    });
    // dom更新前
    onBeforeUpdate(() => {
      console.log("onBeforeUpdate");
    });
    // dom更新后
    onUpdated(() => {
      console.log("onUpdated");
      //data.num += 1;//触发死循环
    });
    // 事件和方法
    const handleClick = () => {
      alert("你好！");
    };
    const submit = () => {
      alert(`${data.username}的建议是${data.userInput}`);
    };
    const handleblur = () => {
      console.log("失去焦点了");
      if (!data.userphone) {
        alert("手机号是必填项！");
      }
    };
    const handlefocus = () => {
      console.log("获取焦点了");
    };
    const handleInput = () => {
      // 手机号正则验证
      if (!/^[1][3,4,5,7,8][0-9]{9}$/.test(data.userphone)) {
        console.log("不符合手机号！");
      } else {
        console.log("符合手机号！");
      }
    };

    return {
      ...toRefs(data),
      handleClick,
      submit,
      handleblur,
      handlefocus,
      handleInput,
    };
  },
};
</script>